package com.woniuxy.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.woniuxy.controller.info.LoginUserInfo;
import com.woniuxy.dao.VoteRoleDao;
import com.woniuxy.util.ObjectRedisTemplate;
import com.woniuxy.util.Result;
import com.woniuxy.util.WoniuxyBeanCopyUtil;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class LoginSuccessHandler implements AuthenticationSuccessHandler {
    private ObjectMapper objectMapper = new ObjectMapper();
    @Resource
    private VoteRoleDao voteRoleDao;
    @Resource
    private ObjectRedisTemplate objectRedisTemplate;
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/json;charset=utf8");

        LoginUserInfo loginUserInfo = WoniuxyBeanCopyUtil.copyOne(
                authentication.getPrincipal(), LoginUserInfo.class);

        //在Redis只存入一个accountId
        request.getSession().setAttribute("AccountId",loginUserInfo.getAccountId());
        Result result = Result.success(200, "登陆成功", loginUserInfo);
            String json = objectMapper.writeValueAsString(result);
            response.getWriter().write(json);
            response.getWriter().flush();
    }
}
